<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/10/19
 * Time: 14:28
 */
namespace work{
    use app\ctr;
    use C\lib\Db;
    use C\lib\Net;
    use C\lib\Session;
    use C\mod\uaddres;
    use C\mod\user;
    use C\mod\order;
    use C\lib\Sms;
    use C\lib\Text;
    use C\mod\sms_routing;
    use C\mod\voucher;
    use C\lib\Wxapi;
    use C\mod\code;
    use C\lib\Oss;
    use C\lib\Ditu;


    class buser extends ctr{
        public function __construct() {
            Db::connect();
        }

        public function sendCode(){
            //echo 444;exit;
            Db::connect();
            if(Text::isPhone($_POST['phone'])){
            }  else {
                $this->writeJson(0, '请输入十一位手机号');
            }
            if($time=sms_routing::get(['phone' => $_POST['phone']],['id', 'DESC'])) {
                if ($time->time_add >= $_SERVER['REQUEST_TIME'] - 60 && !empty($time)) {
                    $this->writeJson(0, '验证已发送，请一分钟后再次发送');
                }
            }
            $code = rand(100000, 999999);
            $scode=new \C\mod\sms_routing();
            $scode->set([
                'phone' => $_POST['phone'],
                'state' => 3,
                'code' => $code,
                'time_add' => $_SERVER['REQUEST_TIME']
            ]);

            if($scode->create()){
                $sms=Sms::send('【便递科技】您的验证码为:' . $code . '请您妥善保管,十分钟内有效！', $_POST['phone']);
                if($sms){
                    $this->writeJson(1);
                }else{
                    $this->writeJson(0);
                }
            }else{
                $this->writeJson(0);
            }
        }
        // --- 用户登录接口 ---

        public function weixin() {

            Session::start();//session_start
            if(isset($_GET['code']) && $_GET['code'] != ''){
                if($r = Net::get('https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx08a944d5a385e626&secret=a7c5fb282f444d28647f69657fcb8fe0&code='.$_GET['code'].'&grant_type=authorization_code')){
                    $j = json_decode($r);//var_dump($j);exit;
                    if(!isset($j->errcode)) {
                        $openid = $j->openid;
                        $access_token=Wxapi::getAccessToken();//不能用上边$j得到的token  会过期的  必须用这个

                        $user=user::get(['wx_openid'=>$openid]);
                        if($user){
                            // --- 存在则直接登录成功 ---
                            $_SESSION['user.id'] = $user->id;
                            $_SESSION['user.wx_openid'] = $openid;
                            // --- 跳转到之前页面 ---
                            header('Location: '.$_SESSION['location']);
                            unset($_SESSION['location']);
                        }else{
                            // --- 用户不存在,存在Session里 ---
                            $_SESSION['user.wx_openid'] = $openid;
                            $_SESSION['user.access_token'] = $access_token;

                            $this->loadView('bdkd/sign/main');
                        }
                    } else
                        $this->writeJson(-2, 'errcode: '.$j->errcode.', errmsg: '.$j->errmsg.'.');
                }else
                    $this->writeJson(-1, 'Network is wrong.');
            }
        }

        /*
         * 微信消息推送
         */
        public function v(){
            //$openid='oCmPBwPvgMjvVVa16p-zyoO9ccCw';
            //$openid='oCmPBwLh4RjCIHa5WwIRqg-PMz-w';
            $openid='oCmPBwPvgMjvVVa16p-zyoO9ccCw';
                  //'oCmPBwE7hZR6QjUO--RvB1Bqr0GU';

            $m=Wxapi::sendInfo($openid,0,12,12);
            //var_dump($b);exit;
        }


        /*
         * 测试登录页面
         */
        public function a(){
            $this->loadView("bdkd/sign/main1");
        }

        /*
         * 测试注册成功获得优惠券
         */
        public function c(){
            Db::connect();
            $user=new \C\mod\user();
            $voucher=new \C\mod\voucher();
            $user->set([
                'phone'=>78866,
                'name'=>'xxy'
            ]);

            if($user->create()){
                $voucher->set([
                    'user_id'=> $user->id,
                    'type'=>1,
                    'discount'=>0.8,
                    'state'=>0,
                    'time_add'=>$_SERVER['REQUEST_TIME']
                ]);
                if($voucher->create()){
                    echo 88;exit;
                }else{
                    echo 99;exit;
                }
            }
        }
        public function login(){
            Session::start();
            Db::connect();

           // $this->writeJson(0,$_SESSION['user.id']);
//
//$_SESSION['user.wx_openid']='oCmPBwPvgMjvVVa16p-zyoO9ccCw';
//            $_SESSION['user.access_token']=00;
//            $_SESSION['user.id']=30;
            if(isset($_SESSION['user.wx_openid']) && isset($_SESSION['user.access_token'])){
                $user=user::get(['wx_openid'=>$_SESSION['user.wx_openid']]);
               // var_dump($_SESSION);
               // var_dump($user);
                if(empty($user)){

                    $info=Net::get("https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$_SESSION['user.access_token']."&openid=".$_SESSION['user.wx_openid']."&lang=zh_CN");
                    $res=json_decode($info,true);
                    $data['name'] = $res['nickname'];
                    $data['path'] = $res['headimgurl'];
                    $data['sex'] = $res['sex'];
                    $data['wx_openid']=$_SESSION['user.wx_openid'];

                    if(Text::isPhone($_POST['phone'])){
                        $phone=user::get(['phone'=>$_POST['phone']]);
                        if($phone){
                            $this->writeJson(0,'此手机号已注册请不要重复注册!');exit;
                        }else{
                            $data['phone']=$_POST['phone'];
                        }
                    }else{
                        $this->writeJson(0,'请填写手机号!');exit;
                    }
                    if(!empty($_POST['code'])){
                    }else{
                        $this->writeJson(0,'请填写验证码!');exit;
                    }
                    $data['time_add']=$_SERVER['REQUEST_TIME'];

                    $time=sms_routing::get(['phone' => $_POST['phone'],'state'=>3],['id', 'DESC']);
                    // --- 验证码在十分钟内有效 ---
                    if($time->time_add >= $_SERVER['REQUEST_TIME']-60000000 && !empty($time)){
                        if($time->code == $_POST['code']){
                        } else {
                            $this->writeJson(0,'验证码错误!');exit;
                        }
                    }else {
                        $this->writeJson(0,'验证码超时!');exit;
                    }

                    $user=new user();

                    $user->set($data);

                    if($user->create()){
                        //获得优惠券
                        $voucher=new voucher();
                        $voucher->set([
                            'user_id'=> $user->id,
                            'type'=>1,//2邮寄 1代取
                            'discount'=>2,
                            'state'=>0,
                            'time_add'=>$_SERVER['REQUEST_TIME'],
                            'end_time'=>$_SERVER['REQUEST_TIME']+15*24*3600
                        ]);
                        $voucher->create();
                        $voucher2=new voucher();
                        $voucher2->set([
                            'user_id'=> $user->id,
                            'type'=>2,//1寄快递 2取快递
                            'discount'=>0.8,
                            'state'=>0,
                            'time_add'=>$_SERVER['REQUEST_TIME'],
                            'end_time'=>$_SERVER['REQUEST_TIME']+15*24*3600
                        ]);
                        $voucher2->create();
                        $this->writeJson(1);exit;
                    }else{
                        $this->writeJson(0,'登录失败!');exit;
                    }
                }else{
                    $this->writeJson(1);exit;
                }
            }else{
                //var_dump($_SESSION);
               // echo "调回入口文件";exit;
                header('Location: http://s.biandikeji.com/work/bpost/main');
            }

        }


        /*
         * 个人认证页面
         */
        public function personal(){
            Db::connect();
            Session::start();
            if(isset($_SESSION['user.id'])){
                $arr=$this->info($_SESSION['user.id']);
                //var_dump($arr['data']);
                //$worker->head_oss != '' ? STATIC_PATH.$worker->head_oss : '',
                $img['idcard_oss1']=$arr['data']->idcard_oss1 !='' ? STATIC_PATH.$arr['data']->idcard_oss1 : '';
                $img['idcard_oss2']=$arr['data']->idcard_oss1 !='' ? STATIC_PATH.$arr['data']->idcard_oss2 : '';
                $this->loadView("bdkd/user/personal",['data'=>$arr['data'],'area'=>$arr['area'],'img'=>$img]);
            }
        }
        /*
         * 我的地址页面
         */
        public function uaddres(){
            Db::connect();
            Session::start();
            if(isset($_SESSION['user.id'])){
                $data=$this->info($_SESSION['user.id']);
                $this->loadView("bdkd/user/udizhi",['area'=>$data['area']]);
            }
        }

        /*
         * 修改用户信息
         */
        public function upUser(){
            Session::start();
            //var_dump($_POST);exit;
           // $_SESSION['user.id']=24;
            if(isset($_SESSION['user.id'])){
               // var_dump($_POST);exit;
                $data = [];
                if(isset($_POST['name'])){
                    $data['name']=str_replace(" ",'',$_POST['name']);
                }else{
                    $this->writeJson(0,'请填写姓名！');exit;
                }
                if(isset($_POST['idcard'])){
                    if(!Text::isIdCard($_POST['idcard'])){
                        $this->writeJson(0,'请填写正确格式的身份证号！');exit;
                    }else{
                        $data['idcard']=$_POST['idcard'];
                    }

                }else{
                    $this->writeJson(0,'请填写身份证号！');exit;
                }
                if(isset($_POST['birthday'])){
                    $data['birthday']=str_replace(" ",'',$_POST['birthday']);
                }else{
                    $this->writeJson(0,'请填生日！');exit;
                }
                if(isset($_POST['identity'])){
                    $data['identity']=$_POST['identity'];
                }else{
                    $this->writeJson(0,'请选择身份！');exit;
                }
                if(isset($_POST['bir_type'])){
                    $data['bir_type']=1;
                }
                if(isset($_POST['addres'])){
                   $data['addres']=str_replace(" ",'',$_POST['addres']);
                }
                if(isset($_POST['path1']) && !empty($_POST['path1'])){//选传
                    $str=strstr($_POST['path1'],'/9j');

                    //echo 222;
                    //上传身份证照片2张
                    if(strlen($str)<=2097152){

                        Oss::connect();
                        do {
                            $h = 'upload/img/' . date('Y') . '/' . date('m') . '/' . md5($_SESSION['user.id'] . uniqid() . rand(1000, 9999)) . '.jpg';
                        } while (Oss::isExist($h));
                        if(Oss::putFile($h, base64_decode($str))){

                            $data['idcard_oss1']=$h;
                        }else{

                            $this->writeJson(0,'图片上传失败!');exit;
                        }

                        //var_dump($data);
                    }else{
                        $this->writeJson(0,'请上传小于2M的图片');exit;
                    }
                }
                if(isset($_POST['path2']) && !empty($_POST['path2'])){//选传
                    $str=strstr($_POST['path2'],'/9j');
                    //上传身份证照片2张
                    if(strlen($str)<=2097152){
                        Oss::connect();
                        do {
                            $h1 = 'upload/img/' . date('Y') . '/' . date('m') . '/' . md5($_SESSION['user.id'] . uniqid() . rand(1000, 9999)) . '.jpg';
                        } while (Oss::isExist($h1));
                        Oss::putFile($h1, base64_decode($str));
                        $data['idcard_oss2']=$h1;
                    }else{
                        $this->writeJson(0,'请上传小于2M的图片');
                    }
                }

                $data['state']=1;
               //var_dump($data);

                $bduser=user::get(['id'=>$_SESSION['user.id']]);
                $bduser->set($data);
                if($bduser->update()){
                    $this->writeJson(1);
                }else{
                    $this->writeJson(0,'修改失败');
                }
            }else
                $this->writeJson(0,'请您登录');
        }

        /*
         * 修改手机号
         */
        public function upphone(){
            Session::start();
            if(isset($_SESSION['user.id'])){
                if(empty($_POST['phone'])){
                    $this->writeJson(0,'请输入手机号!');exit;
                }else{
                    if(!Text::isPhone($_POST['phone'])){
                        $this->writeJson(0,'请输入正确格式的手机号!');exit;
                    }
                }
                $up=user::get(['id'=>$_SESSION['user.id']]);
                $up->set([
                    'phone'=>$_POST['phone']
                ]);
                if($up->update()){
                    $this->writeJson(1);exit;
                }else{
                    $this->writeJson(0,'手机号修改失败!');exit;
                }
            }
        }

        /*
         * 添加(修改)用户地址
         */

        public function addarea(){
            Db::connect();
            Session::start();

            if(isset($_SESSION['user.id'])){

                // var_dump($_POST);

                if(!empty($_POST['location'])){
                }else{
                    $this->writeJson(0,'请输入地址!');exit;
                }
                if(isset($_POST['type'])){
                }else{
                    $this->writeJson(0,'缺少type参数!');exit;
                }

                if(!empty($_POST['address'])){

                    if(!Ditu::curlGetWeb(str_replace(" ",'',$_POST['location'].$_POST['address']))){
                        $this->writeJson(0,'请填写正确的地址!');exit;
                    }
                }else{
                    $this->writeJson(0,'请填写详细地址!');exit;
                }
                $address=Ditu::curlGetWeb(str_replace(" ",'',$_POST['location'].$_POST['address']));
                // var_dump($address);
                // $res=Ditu::bdTOgcj($address['lat'],$address['lng']);
                $is_area=uaddres::get(['user_id'=>$_SESSION['user.id'],'type'=>0]);
                if($is_area){
                    $is_area->set([
                        'user_id'=>$_SESSION['user.id'],
                        'addres' => str_replace(" ",'',$_POST['location'].$_POST['address']),
                        'lat' => $address['lat'],
                        'lng' => $address['lng'],
                        'type' => $_POST['type']
                    ]);
                    $res=$is_area->update();
                }else{
                    $addres=new uaddres();
                    $addres->set([
                        'user_id'=>$_SESSION['user.id'],
                        'addres' => str_replace(" ",'',$_POST['location'].$_POST['address']),
                        'lat' => $address['lat'],
                        'lng' => $address['lng'],
                        'type' => $_POST['type']
                    ]);
                    $res=$addres->create();
                }


                // var_dump($address);//exit;

                if($res){
                    $this->writeJson(1);
                }else{
                    $this->writeJson(0,'提交失败!');
                }
//
//                $data=uaddres::get(['user_id'=>$_SESSION['user.id'],'lat'=>$address['lat'],'lng'=>$address['lng']]);
//                if($data){
//                    $this->writeJson(1);
//                }else{
//
//                }
            }else
                $this->loadView('bdkd/sign/main');

        }

        /*
         * 用户信息
         */
        public function userInfo(){
            Db::connect();
            Session::start();
           // var_dump($_SESSION);//exit;
           // $_SESSION['user.id']=30;
            if(isset($_SESSION['user.id'])){
                //var_dump($_SESSION);
                $arr=$this->info($_SESSION['user.id']);
                //var_dump($arr);
                $this->loadView("bdkd/user/user",['data'=>$arr['data'],'voucher'=>$arr['voucher']]);
            }else{
                //调到入口文件
                header('Location: http://s.biandikeji.com/work/bpost/main');
            }
        }
        /*
         * 用户信息
         */
        public function info($user_id){
           // var_dump($user_id);
            $data=[];
            $data=user::get(["id"=>$user_id]);
            $voucher=voucher::row($user_id);
            $area=uaddres::get(['user_id'=>$_SESSION['user.id'],'type'=>0]);

            $arr['data']=$data;
            $arr['voucher']=$voucher;
            $arr['area']=$area;
            return $arr;
        }

        /*
         * 与我合作
         */
        public function cooperate(){
            Session::start();
            if(isset($_SESSION['user.id'])){
                $this->loadView("bdkd/user/cooperate");
            }
        }



        /*
         * 邀请码页面
         */
        public function code(){
            Db::connect();
            Session::start();
            if(isset($_SESSION['user.id'])){
                $is_get=[];
                $is_get=code::get(['user_id'=>$_SESSION['user.id']]);
                //var_dump($is_get->phone);
                $this->loadView('bdkd/user/yaoqing',['is_get'=>$is_get]);
            }
        }
        /*
         *填写邀请码获得奖励
         */
        public function addCode(){
            Session::start();
            Db::connect();
            if(isset($_SESSION['user.id'])){
               // $this->writeJson(0,$_POST['code']);exit;
                if(empty($_POST['code'])){
                    $this->writeJson(0,'请填写邀请码');exit;
                }else{
                    if(!Text::isPhone($_POST['code'])){
                        $this->writeJson(0,'手机号格式不正确！');exit;
                    }
                }
                //查询手机号是否已经注册 没有注册不能填写
                $uphone=user::get(['phone'=>$_POST['code']]);
                if(!$uphone){
                    $this->writeJson(0,'此手机号不是推荐人！');exit;
                }
                //查询是否是已注册用户  不能填写自己的手机号作为邀请码
                $user=user::get(['id'=>$_SESSION['user.id']]);

                if($user->phone==$_POST['code']){
                    $this->writeJson(0,'不能填写自己的手机号作为邀请码！');exit;
                }

                if($user){

                    $is_get=code::get(['user_id'=>$_SESSION['user.id']]);//只允许填写一次邀请码
                   // var_dump($is_get);exit;
                   // $this->writeJson(0,$is_get);exit;
                    if(!$is_get){
                        //根据手机号获得优惠券
                    //$this->writeJson(0,'333333');exit;
                        try {
                            Db::beginTransaction();
                            $voucher=new voucher();
                            $voucher->set([
                                'user_id'=>$user->id,
                                'type'=>2,
                                'discount'=>0.9,
                                'state'=>0,
                                'time_add'=>$_SERVER['REQUEST_TIME'],
                                'end_time'=>$_SERVER['REQUEST_TIME']+15*24*3600
                            ]);
                            $addvoucher=$voucher->create();
                            //邀请码记录
                            $code=new code();
                            $code->set([
                                'user_id'=>$_SESSION['user.id'],
                                'phone'=>$_POST['code'],
                                'time_add'=>$_SERVER['REQUEST_TIME']
                            ]);
                            $addcode=$code->create();
                            if ($addvoucher && $addcode) {
                                Db::commit();
                               // echo 88;
                                $this->writeJson(1);exit;
                            } else {
                                Db::rollBack();
                               // echo 55;
                                $this->writeJson(0,'失败!');exit;
                            }
                        } catch (\Exception $e) {
                            Db::rollBack(); // 执行失败，事务回滚
                            //echo 33;
                            $this->writeJson(0,'失败!');exit;
                        }
                    }else{
                        //echo 11;
                        $this->writeJson(0,'您已填写过邀请码!');exit;
                    }
                }else{
                    //echo 22;
                    $this->writeJson(0,'此邀请人无效!');exit;
                }
            }
        }


        /*
         * 我的优惠券页面
         */

        public function quan(){
            Session::start();
            Db::connect();
            if(isset($_SESSION['user.id'])){
                //var_dump($_GET);exit;
                $type='';//判断是从个人中心优惠券页面进入优惠券页面还是 从支付页面进入优惠券页面
                if(isset($_GET['type'])){
                    $type=$_GET['type'];
                }
                $id='';
                if(isset($_GET['id'])){
                    $id=$_GET['id'];
                }
                $wtype='';//1从取快递支付页面进入优惠券  2从寄快递()支付页面进去 3物流托运
                if(isset($_GET['wtype'])){
                    $wtype=$_GET['wtype'];
                }


                $list1=[];
                $list2=[];
                $time=$_SERVER['REQUEST_TIME'];
                //查询所有的优惠券 不管过期不过期 不要已使用过得
                $voucher=voucher::getList(['user_id'=>$_SESSION['user.id'],['state','!=',1]]);
                //$voucher=voucher::getList(['user_id'=>$_SESSION['user.id'],'state'=>0,['time_add','<',$time],['end_time','>',$time]]);
                foreach ($voucher as $value){
                    if($time<$value->time_add || $time>$value->end_time){//过期
                        $list2[]=[
                            'id'=>$value->id,
                            'type'=>$value->type,
                            'discount'=>$value->discount,
                            'end_time'=>$value->end_time
                        ];
                    }else {
                        $list1[]=[
                            'id'=>$value->id,
                            'type'=>$value->type,
                            'discount'=>$value->discount,
                            'end_time'=>$value->end_time
                        ];
                    }
                }

//                var_dump($list1);
//                 var_dump($list2);exit;
                $this->loadView("bdkd/user/quan",['list1'=>$list1,'list2'=>$list2,'type'=>$type,'id'=>$id,'wtype'=>$wtype]);
            }
        }
        /*
         * 删除优惠券
         */
        public function delVoucher(){
            Session::start();
            if(isset($_SESSION['user.id'])){
                if(empty($_POST['id'])){
                    $this->writeJson(0,'请选择要删除的优惠券!');
                    exit;
                }
                $dlv=voucher::delete(['id'=>$_POST['id']]);
                if($dlv){
                    $this->writeJson(1);
                }else{
                    $this->writeJson(0,'删除失败!');
                }
            }
        }
    }
}